package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.Const;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HCarVisitorMapper;
import com.flea.hclv.model.dao.HProductMapper;
import com.flea.hclv.model.dao.HTimeTableMapper;
import com.flea.hclv.model.dao.HVisitorMapper;
import com.flea.hclv.model.entity.HCarVisitor;
import com.flea.hclv.model.entity.HProduct;
import com.flea.hclv.model.entity.HTimeTable;
import com.flea.hclv.model.entity.HVisitor;
import com.flea.hclv.service.HCarVisitorService;
import com.flea.hclv.util.ExportExcelUtil;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: project
 * @description: 游客选座
 * @author: shiliqiang
 * @create: 2019-01-02 11:11
 * @version: 1.0
 */
@Service
public class HCarVisitorServiceImpl implements HCarVisitorService {

    @Autowired
    private HCarVisitorMapper hCarVisitorMapper;
    @Autowired
    private HTimeTableMapper hTimeTableMapper;
    @Autowired
    private HVisitorMapper hVisitorMapper;
    @Autowired
    private HProductMapper hProductMapper;
    @Override
    public ServerResponse<String> saveSeatNumber(String userId, String model) throws Exception {
        JSONObject jsonObject = JSON.parseObject(model);
        JSONArray carVisitors = JSON.parseArray(jsonObject.getString("seats"));
        int dataSize = carVisitors.size();
        if (dataSize==0){
            return ServerResponse.createByErrorMessage("请为游客选择座位！");
        }
        String seatId =carVisitors.getJSONObject(0).getString("seatId");
        HCarVisitor entity1 = hCarVisitorMapper.selectByPrimaryKey(seatId);
        List<HCarVisitor> list = hCarVisitorMapper.selectByTimeTableId(entity1.getTimetableId(),null);
        //同一班期，车辆 一个游客只有一个座位。
        for (HCarVisitor carVisitor : list){
            for (int i =0;i<dataSize;i++){
                jsonObject = carVisitors.getJSONObject(i);
                String visitorId = jsonObject.getString("visitorId");
                String visitorId1 = carVisitor.getVisitorId();
                if (visitorId1==null){
                    continue;
                }
                if (carVisitor.getVisitorId().equals(visitorId)){
                    HVisitor hVisitor = hVisitorMapper.selectByPrimaryKey(visitorId);
                    return ServerResponse.createByErrorMessage("游客:"+hVisitor.getZhName()+"已经下单并选择座位。");
                }
            }
        }
        for (int i =0;i<carVisitors.size();i++){
            jsonObject = carVisitors.getJSONObject(i);
            String id = jsonObject.getString("seatId");
            String visitorId = jsonObject.getString("visitorId");
            if (StringUtils.isBlank(id)){
                throw new Exception("选座ID为空");
            }
            if (StringUtils.isBlank(visitorId)){
                throw new Exception("游客ID为空");
            }
            HCarVisitor entity = hCarVisitorMapper.selectByPrimaryKey(id);
            if (entity==null){
                throw new Exception("座位不存在");
            }
            //isUSer 1使用中 0未使用
            Integer isUse = entity.getIsUse();
            if (isUse==1){
                HVisitor hVisitor = hVisitorMapper.selectByPrimaryKey(visitorId);
                throw  new Exception(entity.getSeatNumber()+"号座位已经有人，请为"+hVisitor.getZhName()+"游客选择其他座位！");
            }else if (isUse==0 && StringUtils.isEmpty(entity.getVisitorId())){
                entity.setIsUse(1);
                entity.setModifyUser(userId);
                entity.setVisitorId(visitorId);
                int row = hCarVisitorMapper.updateByPrimaryKey(entity);
                if (row!=1){
                    throw new Exception("选座失败");
                }
            }else {
                throw new Exception("发生错误");
            }
        }
        return ServerResponse.createBySuccessMessage("选座成功");
    }

    @Override
    public ServerResponse<String> selectExportVisitorSeats(String timeTableId, HttpServletResponse response) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        HTimeTable hTimeTable = hTimeTableMapper.selectByPrimaryKey(timeTableId);
        if (hTimeTable==null){
            return ServerResponse.createByErrorMessage("班期不存在");
        }
        Date timeTableDate = hTimeTable.getDate();
        HProduct hProduct = hProductMapper.selectByPrimaryKey(hTimeTable.getProductId());
        if (hProduct==null){
            return ServerResponse.createByErrorMessage("产品不存在");
        }
        List<HVisitor> visitors = hVisitorMapper.selectByTimeTableIdJoinVisitorId(timeTableId);
        JSONArray jsonArray = new JSONArray();
        if (CollectionUtils.isNotEmpty(visitors)){
            for (HVisitor visitor : visitors) {

                JSONObject jsonObject = new JSONObject();
                String type = visitor.getType();


                jsonObject.put("姓名", visitor.getZhName());
                jsonObject.put("英文名", visitor.getEnName());
                jsonObject.put("游客类型", setVisitorType(type));
                String sex=visitor.getSex();
                jsonObject.put("性别",setSexValue(sex));
                String certificates = visitor.getCertificates();

                jsonObject.put("证件类型", setCertificatesTypeValue(certificates));
                jsonObject.put("证件号码", visitor.getCertificatesNumber());
                Date date = visitor.getBirthDate();

                String dateString = formatter.format(date);
                jsonObject.put("出生日期", dateString);
                jsonObject.put("手机号", visitor.getPhone());
                jsonObject.put("车号",visitor.getCarNumber());
                jsonObject.put("座位号",visitor.getSeatNumber());
                jsonObject.put("备注",visitor.getDescription());
                jsonArray.add(jsonObject);
            }
        }


        // 标题
        String title = hProduct.getTitle()+formatter.format(timeTableDate)+"游客名单";
        // 文件名称
        title = title.replace(" ", "_");
        String fileName = title+".xls";
        String[] titles = {  "姓名", "英文名", "游客类型","性别", "证件类型", "证件号码", "出生日期",
                "手机号","车号","座位号","备注" };
        String tempPath = System.getProperty("java.io.tmpdir");
        // 路径
        //String path = "D:\\doc";
        ExportExcelUtil.createExcel(response, tempPath, fileName, title, titles,jsonArray);
        ServerResponse<String> response1 = downLoadFile(tempPath,fileName,response);
        if (!response1.isSuccess()){
            return response1;
        }
        return ServerResponse.createBySuccess();
    }



    @Override
    public ServerResponse<String> cancelSeatNumber(String timeTableId, List<HVisitor> visitors) {
        if (StringUtils.isBlank(timeTableId)){
            return ServerResponse.createByErrorMessage("班期ID为空");
        }
        if (CollectionUtils.isEmpty(visitors)){
            return ServerResponse.createByErrorMessage("游客为空");
        }
        List<HCarVisitor> carVisitors = hCarVisitorMapper.selectByTimeTableIdAndVisitorIds(timeTableId,visitors);
        if (CollectionUtils.isEmpty(carVisitors)){
            return ServerResponse.createByErrorMessage("没有找到座位信息");
        }
        List<HCarVisitor> newList = Lists.newArrayList();
        for (HCarVisitor entity : carVisitors){
            entity.setVisitorId(StringUtils.EMPTY);
            entity.setIsUse(0);
            newList.add(entity);
        }
        int row = hCarVisitorMapper.updateBatch(newList);
        if (row!=newList.size()){
            return ServerResponse.createByErrorMessage("批量更新座位失败");
        }
        return ServerResponse.createBySuccess();
    }


    @Override
    public ServerResponse<Map<String, Object>> selectByTimeTableId(String userId, String timeTableId, Integer isGo) {
        List<HCarVisitor> data = hCarVisitorMapper.selectByTimeTableId(timeTableId,isGo);
        if (CollectionUtils.isNotEmpty(data)){
            int seatNumber = 57;
            int size = data.size();
            int forSize = size/seatNumber;
            Map<String,Object> map = Maps.newHashMap();
            for (int i = 1; i <= forSize; i++){

                List<HCarVisitor> list = hCarVisitorMapper.selectByTimeTableIdAndCarNumber(timeTableId,i);
//                for (HCarVisitor entity : data){
//                    if (entity.getCarNumber()==i){
//                        list.add(entity);
//                    }
//                }
                map.put(String.valueOf(i),list);
            }
            return ServerResponse.createBySuccess(map);

        }
        return ServerResponse.createByErrorMessage("没有找到座位信息");
    }

    @Override
    public ServerResponse<Map<String, Object>> createCarSeat(String userId, String timeTableId) {
        //车号  第几个车
        int carNumber;
        //定义座位数57座
        int carSeatNumber = 57;
        //定义第一个座位号1
        int firstNumber = 1;
        //座位使用状态  0未使用  1已使用
        int isUse = 0;
        //是否出发车   1出发车 0回来车
        int isGo = 1;
//        int isBack = 0;
        //查询班期是否存在
        HTimeTable hTimeTable = hTimeTableMapper.selectByPrimaryKey(timeTableId);
        if (hTimeTable==null){
            return ServerResponse.createByErrorMessage("班期不存在");
        }
        if (StringUtils.equals(hTimeTable.getValid(),"N")){
            return ServerResponse.createByErrorMessage("班期已删除");
        }
        List<HCarVisitor> createCarVisitors = Lists.newArrayList();
        List<HCarVisitor> oldData = hCarVisitorMapper.selectByTimeTableId(timeTableId, null);
        if (CollectionUtils.isEmpty(oldData)){
            carNumber=1;
        }else {
            //判断是否坐满，未坐满不能创建座位
            for (HCarVisitor entity : oldData){
                if (entity.getIsUse()==0){
                    return selectByTimeTableId(userId,timeTableId,null);
                }
            }
            //计算第几车
            int dataSize = oldData.size();
            //当前车次
            int carNum = dataSize/carSeatNumber;
            //将要创建的车次
            carNumber = carNum+1;

        }

        //创建57个座位号 ()
        for (int i =firstNumber; i <= carSeatNumber; i++ ){
                HCarVisitor go = new HCarVisitor();
                go.setId(FleaStringUtils.getGenerateUUID());
                go.setCreateUser(userId);
                go.setCarNumber(carNumber);
                go.setSeatNumber(i);
                go.setIsUse(isUse);
                go.setTimetableId(timeTableId);
                go.setIsGo(isGo);
                createCarVisitors.add(go);
        }
        int row = hCarVisitorMapper.insertBatch(createCarVisitors);
        if (row!=createCarVisitors.size()){
            return ServerResponse.createBySuccessMessage("创建座位失败");
        }
        //返回出发车所有的座位信息
        return selectByTimeTableId(userId,timeTableId,null);


    }
    //性别
    public static String setSexValue(String sex){
        if (StringUtils.isBlank(sex)){
            sex = StringUtils.EMPTY;
        }else if (StringUtils.equals(sex,HConstant.SEX_NAN)){
            sex = "男";
        }else if (StringUtils.equals(sex,HConstant.SEX_NV)){
            sex = "女";
        }
        return sex;
    }
    //证件类型
    public static String setCertificatesTypeValue(String certificatesType){
        switch (certificatesType) {
            case HConstant.D_CERTIFICATES_ID:
                certificatesType = Const.CertificatesTypeEnum.D_CERTIFICATES_ID
                        .getValue();
                break;
            case HConstant.D_CERTIFICATES_PASSPORT:
                certificatesType = Const.CertificatesTypeEnum.D_CERTIFICATES_PASSPORT
                        .getValue();
                break;
            case HConstant.D_CERTIFICATES_PASS:
                certificatesType = Const.CertificatesTypeEnum.D_CERTIFICATES_PASS
                        .getValue();
                break;
            default:
                break;
        }
        return certificatesType;
    }
    //游客类型
    public static String setVisitorType(String visitorType) {
        if (visitorType.equals(HConstant.D_VISITOR_TYPE_CHILDREN)){
            visitorType = Const.VisitorTypeEnum.D_VISITOR_TYPE_CHILDREN.getValue();
        }
        if (visitorType.equals(HConstant.D_VISITOR_TYPE_OTHER)){
            visitorType = Const.VisitorTypeEnum.D_VISITOR_TYPE_OTHER.getValue();
        }
        if (visitorType.equals(HConstant.D_VISITOR_TYPE_ADULT)){
            visitorType = Const.VisitorTypeEnum.D_VISITOR_TYPE_ADULT.getValue();
        }
        if (visitorType.equals(HConstant.D_VISITOR_TYPE_OLD)){
            visitorType = Const.VisitorTypeEnum.D_VISITOR_TYPE_OLD.getValue();
        }
        return visitorType;
    }
    //下载
    public static ServerResponse<String> downLoadFile(String tempPath,String fileName,HttpServletResponse response){
        File tmpfile = null;

        FileInputStream ips = null;
        ServletOutputStream out = null;
        try {
            tmpfile =	 new File(tempPath+"\\"+fileName);
            if (!tmpfile.exists()) {
                // 如果文件不存在就跳出
                return ServerResponse.createBySuccessMessage("导出文件失败，请稍后进行尝试");
            }
            ips = new FileInputStream(tmpfile);
            response.setContentType("multipart/form-data");
            //为文件重新设置名字，采用数据库内存储的文件名称
            response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"),"ISO8859-1") + "\"");
            out = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if (out!=null){
                    out.close();
                }
                if (ips!=null){
                    ips.close();
                }
                if (tmpfile!=null){
                    tmpfile.delete();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ServerResponse.createBySuccess();
    }

}
